package lium.lbs.lbsim.activity

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.widget.Toast
import cn.jpush.im.android.api.JMessageClient
import cn.jpush.im.android.api.model.UserInfo
import cn.jpush.im.api.BasicCallback
import com.buz.hjcdriver.bean.LoginResultBean
import com.buz.hjcdriver.bean.RegistResultBean
import com.lmlibrary.Constants
import lium.lbs.lbsim.utils.UserUtils
import com.lmlibrary.bean.ResponseBean
import lium.lbs.lbsim.utils.callbck.DialogCallback
import lium.lbs.lbsim.utils.ToastUtils
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_registuserpwd.*
import lium.lbs.lbsim.R
import lium.lbs.lbsim.jchat.utils.SharePreferenceManager
import lium.lbs.lbsim.jgchat.database.UserEntry
import lium.lbs.lbsim.jgchat.utils.photovideo.takevideo.utils.LogUtils
import lium.lbs.lbsim.utils.SpUtils
import java.util.HashMap

class RegistSetPWDActivity : BaseActivity() {
    private var telPhone: String? = null
    override fun getLayoutId(): Int {
        return R.layout.activity_registuserpwd
    }

    var isforget: Boolean = false
    private var mMyInfo: UserInfo? = null
    var countryCode: String? = null
    override fun initView(savedInstanceState: Bundle?) {
        setTitleWithBack("")
        telPhone = intent.getStringExtra("phone")
        LogUtils.e("body--telPhone" + telPhone)
        setpwd_alert.text = "输入密码"
        addOnClickListeners(R.id.left_img,R.id.btn_submit)
        intent?.let {
            if (intent.hasExtra("isforget")) {
                isforget = intent.getBooleanExtra("isforget", false)
                setpwd_alert.text = "输入新的密码"
            }
            countryCode = intent.getStringExtra("countryCode")
        }
    }

    override fun getNetWorkData() {
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when (v!!.id) {
            R.id.btn_submit -> {
                if (isforget) {
                    resetPWD()
                } else {
                    //login()
                    phoneRegister()
                }
            }
            R.id.left_img -> {
                val intent = Intent(this, LoginActivity::class.java)
                startActivity(intent)
                finish()
            }
        }
    }

    private fun phoneRegister() {
        if (TextUtils.isEmpty(login_pwd.text.toString())) {
            ToastUtils.showToast("密码无效")
            return
        }
        val param = HashMap<String, String>()
        param["phone"] = telPhone.toString()
        param["password"] = login_pwd.text.toString()
        param["countryCode"] = countryCode.toString()
        postData("/member/phoneRegister", param, object : DialogCallback<ResponseBean<RegistResultBean>>(this) {
            override fun onSuccess(response: Response<ResponseBean<RegistResultBean>>) {
                UserUtils.login(response.body().data.memberId + "")
                if (!TextUtils.isEmpty(
                        SpUtils.getInstance().get(
                            Constants.memberId,
                            ""
                        ).toString()
                    ) && !TextUtils.isEmpty(SpUtils.getInstance().get(Constants.phonepw, "").toString())
                ) {
                    loginJIM(
                        SpUtils.getInstance().get(Constants.memberId, "").toString(),
                        SpUtils.getInstance().get(Constants.phonepw, "").toString()
                    )
                } else {
                    val intent = Intent(this@RegistSetPWDActivity, LoginActivity::class.java)
                    intent.putExtra("phone", telPhone.toString())
                    intent.putExtra("password", login_pwd.text.toString())
                    LogUtils.e("body" + telPhone.toString() + login_pwd.text.toString())
                    //intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
                    startActivity(intent)
                }
                finish()

            }
        })
    }

    private fun resetPWD() {
        if (TextUtils.isEmpty(login_pwd.text.toString())) {
            ToastUtils.showToast("密码无效")
            return
        }
        val param = HashMap<String, String>()
        param["phone"] = intent.getStringExtra("phone")
        param["countryCode"] = countryCode.toString()
        param["password"] = login_pwd.text.toString()
        postData("/member/reSetPwd", param, object : DialogCallback<ResponseBean<LoginResultBean>>(this) {
            override fun onSuccess(response: Response<ResponseBean<LoginResultBean>>) {
                ToastUtils.showToast(response.body().msg + "")
                UserUtils.loginOut(true)
                if (!TextUtils.isEmpty(telPhone)) {
                    login()
                } else {
                    val intent = Intent(this@RegistSetPWDActivity, LoginActivity::class.java)
                    intent.putExtra("phone", telPhone.toString())
                    intent.putExtra("password", login_pwd.text.toString())
                    LogUtils.e("body" + telPhone.toString() + login_pwd.text.toString())
                    //intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
                    startActivity(intent)
                }
                finish()
            }
        })


    }

    fun login() {
        val param = HashMap<String, String>()
        param["phone"] = telPhone.toString()
        param["deviceType"] = "android"
        param["password"] = login_pwd.text.toString()

        param["deviceId"] = ""
        param["deviceName"] = ""

        postData("/authorize", param, object : DialogCallback<ResponseBean<LoginResultBean>>(this) {
            override fun onSuccess(response: Response<ResponseBean<LoginResultBean>>) {
                SpUtils.getInstance().put(Constants.phone, telPhone.toString())
                SpUtils.getInstance().put(Constants.phonepw, login_pwd.text.toString())
                loginJIM(response.body().data.memberId, login_pwd.text.toString())
            }
        })
    }

    fun loginJIM(memberId: String, password: String) {
        JMessageClient.login(memberId, "123456", object : BasicCallback() {
            override fun gotResult(responseCode: Int, responseMessage: String) {
                if (responseCode == 0) {
                    mMyInfo = JMessageClient.getMyInfo();
                    LogUtils.e(
                        "myTest-LoginActivity-getAppKey--" + mMyInfo?.getAppKey() + "--getNickname--" + mMyInfo?.getNickname() +
                                "--getUserID--" + mMyInfo?.getUserID() + "--getUserName--" + mMyInfo?.getUserName()
                    )

                    SharePreferenceManager.setCachedPsw(password)
                    val myInfo = JMessageClient.getMyInfo()
                    val avatarFile = myInfo.avatarFile
                    //登录成功,如果用户有头像就把头像存起来,没有就设置null
                    if (avatarFile != null) {
                        SharePreferenceManager.setCachedAvatarPath(avatarFile.absolutePath)
                    } else {
                        SharePreferenceManager.setCachedAvatarPath(null)
                    }
                    val username = myInfo.userName
                    val appKey = myInfo.appKey
                    LogUtils.e("myTest-" + username)

                    var user = UserEntry.getUser(username, appKey)
                    if (null == user) {
                        user = UserEntry(username, appKey)
                        user.save()
                    }
                    UserUtils.login(memberId + "")
                    SpUtils.getInstance().put(Constants.isLogin, true)
                    val intent = Intent(this@RegistSetPWDActivity, lium.lbs.lbsim.activity.MainActivity::class.java)
                    intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
                    startActivity(intent)
                    finish()
                } else {
                    ToastUtils.showToast("登录失败$responseMessage")
                }
            }
        })
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            val intent = Intent(this@RegistSetPWDActivity, LoginActivity::class.java)
            startActivity(intent)
            finish()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }
}

